package com.bp.hearthealth.pulse.lnapps.bp_ui.bp_activity.bp_language_gender.bp_language

import com.bp.hearthealth.pulse.lnapps.bp_db.bp_user.BpUser
import com.bp.hearthealth.pulse.lnapps.bp_db.bp_user.BpUserDao
import com.bp.hearthealth.pulse.lnapps.bp_network.BaseRepository
import com.bp.hearthealth.pulse.lnapps.bp_network.bp_api.ApiBpService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.withContext

class BpLanguageRepository(private val userDao: BpUserDao, private val service: ApiBpService) :
    BaseRepository() {

    suspend fun requestUserBean(id: String) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                var user = userDao.getUser(id)
                if (user == null) {
                    userDao.insertUser(BpUser(id = id, languageList = getLanguageList()))
                    user = userDao.getUser(id)
                } else {
                    if (user.languageList.isEmpty()) {
                        userDao.insertUser(BpUser(id = id, languageList = getLanguageList()))
                        user = userDao.getUser(id)
                    }
                }
                user
            } catch (e: Exception) {
                null
            }
        }
    }

    internal fun getLanguageAndCity(): MutableList<LanguageAndCity> {
        return languageAndCities
    }

    suspend fun insertUser(userId: String) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                var user = userDao.getUser(userId)
                if (user == null) {
                    userDao.insertUser(BpUser(id = userId))
                    user = userDao.getUser(userId)
                }
                user
            } catch (e: Exception) {
                null
            }
        }
    }

    suspend fun updateLanguageInfo(userId: String, languageId: Int) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                userDao.updateLanguageInfo(userId, languageId)
            } catch (e: Exception) {
                0
            }
        }
    }

    suspend fun getLanguagePosition(userId: String) = withContext(Dispatchers.IO) {
        coroutineScope {
            try {
                userDao.getLanguagePosition(userId)
            } catch (e: Exception) {
                0
            }
        }
    }
}